$(function () {
    grtUserInfo()
})

$('#logout').on('click', function () {
    layer.confirm('确认退出登陆吗', {
        icon: 3,
        title: '提示'
    }, function (index) {
        localStorage.removeItem('token')
        location.href = '/login.html'
        layer.close(index);
    })
})

// 同步用户信息
function grtUserInfo() {
    axios({
        url: '/my/userinfo',
        method: 'GET',
        // /my 开头的请求路径，需要在请求头中携带 Authorization 身份认证字段，才能正常访问成功
        // 设置请求头：
        // headers: {
        //     Authorization: localStorage.getItem('token')
        // }
    }).then(res => {
        //成功回调
        // console.log(res.data.data)
        if (res.data.status !== 0) {
            return layui.layer.msg(res.data.message)
        }
        renderAvatar(res.data.data)
    });
}

function renderAvatar(user) {
    let name = user.nickname || user.username
    $('.welcome').html('欢迎&nbsp:' + name)
    if (user.user_pic !== null) {
        $('.avatar-text').hide()
        $(".layui-nav-img").show().attr('src', user.user_pic)
    } else {
        $('.layui-nav-img').hide()
        let first = name[0].toUpperCase()
        $('.avatar-text').show().html(first)
    }
}